var knex = require('../dbhelper').instance();
var Promise = require('bluebird');
module.exports = {
    getlist: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];

                if (condition.key && condition.key.status == 1) {
                    if (typeof (condition.key) == 'string' || ((condition.key.dsname === undefined || condition.key.dsname.length == 0) && (condition.key.dstags === undefined || condition.key.dstags.length == 0) && (condition.key.start === undefined || condition.key.start.length == 0) && (condition.key.end === undefined || condition.key.end.length == 0))) {
                        promiseArray.push(knex('dslist').where('status', '>', '0')
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('dslist').where('status', '>', '0')
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    } else {
                        condition.key.start = condition.key.start || '2000-01-01 00:00:00';
                        condition.key.end = condition.key.end || '3000-01-01 00:00:00';
                        promiseArray.push(knex('dslist').where('status', '>', '0').andWhere('dsname', 'like', '%' + condition.key.dsname + '%').andWhere('dstags', 'like', '%' + condition.key.dstags + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('dslist').where('status', '>', '0').andWhere('dsname', 'like', '%' + condition.key.dsname + '%').andWhere('dstags', 'like', '%' + condition.key.dstags + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    }
                } else {
                    if (typeof (condition.key) == 'string' || (condition.key.dsname.length == 0 && condition.key.dstags.length == 0 && condition.key.start.length == 0 && condition.key.end.length == 0)) {
                        promiseArray.push(knex('dslist')
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('dslist')
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    } else {
                        condition.key.start = condition.key.start || '2000-01-01 00:00:00';
                        condition.key.end = condition.key.end || '3000-01-01 00:00:00';
                        promiseArray.push(knex('dslist').where('dsname', 'like', '%' + condition.key.dsname + '%').andWhere('dstags', 'like', '%' + condition.key.dstags + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('dslist').where('dsname', 'like', '%' + condition.key.dsname + '%').andWhere('dstags', 'like', '%' + condition.key.dstags + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    }
                }

                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    add: function (params) {
        return new Promise(function (resolve, reject) {
            knex('dslist').insert(params).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    finish: function (params) {
        return new Promise(function (resolve, reject) {
            knex('dslist').update({
                'status': 1
            }).where('dsid', params.dsid).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    publish: function (params) {
        /*  if (params.dstype == 1) { */
        return new Promise(function (resolve, reject) {
            knex('dslist').update({
                'status': 2
            }).where('dsid', params.dsid).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
        /*    } else {
               return new Promise(function (resolve, reject) {
                   var merge_tablename = 'dstable_' + params.dsid+'_merge';
                   var tablename='dstable_' + params.dsid;
                   // 事务模式
                   knex.transaction(function (trx) {
                       return Promise.all([
                               knex.raw('DROP table IF EXISTS ' + tablename + ';create table ' + tablename + ' select * from ' + merge_tablename+';DROP table IF EXISTS ' + merge_tablename+';alter table ' + tablename + ' engine = MYISAM').transacting(trx),
                               knex('dslist').update({
                                   'status': 2
                               }).where('dsid', params.dsid).transacting(trx)
                           ])
                           .then(trx.commit)
                           .catch(trx.rollback);
                   }).then(function (data) {
                       return resolve(data);
                   }).catch(function (err) {
                       console.error(err);
                       reject(err);
                   });
               });
           } */
    },
    /*
     *更新数据集名称或数据集标签
     */
    update_dsinfo: function (params, dsid) {
        return new Promise(function (resolve, reject) {
            knex('dslist').update(params).where('dsid', dsid).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    resourcelist: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];
                promiseArray.push(knex.raw('select dsid id,dsname name,\'\' path,dstags,description,createat,dstype,status  from dslist where find_in_set(dsid,(select inputdsids from dslist where dsid=?)) UNION select resourceid id,resourcename name,path,\'\' dstags,\'\' description,createat,\'-2\' dstype,\'\' status  from fileresource where find_in_set(resourceid,(select inputfolderids from dslist where dsid=?)) ORDER BY createat desc', [condition.key, condition.key]).transacting(trx));

                //promiseArray.push(knex.raw('select count(1) total from dslist where find_in_set(dsid,(select inputdsids from dslist where dsid=?))', [condition.key]).transacting(trx));



                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    delete: function (dsid) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];
                promiseArray.push(knex('dslist').where('dsid', dsid).andWhere('status', '0').del().transacting(trx));
                promiseArray.push(knex.schema.dropTableIfExists('dstable_' + dsid).transacting(trx));

                //promiseArray.push(knex.raw('select count(1) total from dslist where find_in_set(dsid,(select inputdsids from dslist where dsid=?))', [condition.key]).transacting(trx));



                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    }
};